/**
 * 描述：jwt-token 验证与解析
 * 作者：Hulk Chen
 * 日期：2021-08-19
*/
import JWT from 'jsonwebtoken';
import expressJwt from 'express-jwt'
import {PRIVATE_KEY, JWT_EXPIRED} from './constant'
const whitePath: string[] =[ '/','/api/login']

// 生成token
export function JWTsign(signObj: object) {
    return JWT.sign(signObj, PRIVATE_KEY, {expiresIn:JWT_EXPIRED, algorithm: 'HS256'})
}

// 验证token是否过期
export const jwtAuth = expressJwt({
    algorithms: ['HS256'],
    secret: PRIVATE_KEY, // 设置密钥
    credentialsRequired: true, // 设置为true表示校验，false表示不校验
    getToken: (req) => {
        if(req.headers.authorization) {
            return req.headers.authorization
        } else if(req.query && req.query.token) {
            return req.query.token
        }
    }
}).unless({
    path: whitePath
})

// jwt-token解析
export function decodeJwtToken(req) {
    
    const token = req.get('Authoriztion')
    return JWT.verify(token, PRIVATE_KEY)
}


